﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ServiceStack.Text;
using ServiceStack.Text.Json;
using System.IO;
using System.Text;
namespace YmtAuth.Web
{
    public static class HttpExtend
    {
        public static string GetRequestString(this HttpContext context, string key, string defVal = "")
        {
            if (string.IsNullOrEmpty(key)) return defVal;
            if (context == null) return defVal;
            var getVal = context.Request[key];
            if (string.IsNullOrEmpty(getVal)) return defVal;
            return getVal;
        }
        public static string GetRequestFormString(this HttpContext context, string key, string defVal = "")
        {
            if (string.IsNullOrEmpty(key)) return defVal;
            if (context == null) return defVal;
            var getVal = context.Request.Form[key];
            if (string.IsNullOrEmpty(getVal)) return defVal;
            return getVal;
        }
        public static void ResposeJson(this HttpContext context, object val, bool isEnd = false, int responseCode = 200)
        {
            if (context == null) return;
            context.Response.ContentType = "text/json";
            JsConfig.IncludeNullValues = true;
            context.Response.Write(ServiceStack.Text.JsonSerializer.SerializeToString(val));
            context.Response.StatusCode = responseCode;
            if (isEnd) context.Response.End();
        }

        public static T DeserializeFormString<T>(this HttpContext context, string rKey, T defVal = default(T))
        {
            try
            {
                using (var reader = new StreamReader(context.Request.InputStream, Encoding.Unicode))
                {
                    // This will equal to "charset = UTF-8 & param1 = val1 & param2 = val2 & param3 = val3 & param4 = val4"
                    string values = reader.ReadToEnd();
                    return JsonSerializer.DeserializeFromString<T>(values);
                }
                //var getVal = context.GetRequestFormString(rKey);
                //return JsonSerializer.DeserializeFromString<T>(getVal);
            }
            catch
            {
                return defVal;
            }
        }
    }
}